/*
* Copyright (C) 2020 ~ 2023 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/


#include "MkHttpHooker/MkHttpHooker.h"
#include "MkHttp/MkHttpResponse.h"
#include "MkEvent/MkEvent.h"
#include "MkEvent/MkEventPool.h"
#include "MkEvent/MkTimer.h"
#include <MkUtil/MkLog.h>
#include <signal.h>
#include <MkUtil/MkBase64.h>

MkVector<CMkEvent *> VecEvent;
BOOL g_bRun = TRUE;
void SigHandle(int sig)
{
    if (sig == SIGINT) {
        g_bRun = FALSE;
    }
};

int main(int argc, char ** argv)
{
#ifdef _WIN32
    WSADATA WSAData;
    WSAStartup(0x101, &WSAData);
#else
    //signal(SIGPIPE, SIG_IGN);  //ignore sigpipe
    //signal(SIGPIPE, SIG_IGN);
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGPIPE);
    sigprocmask(SIG_BLOCK, &set, NULL);
#endif
    //MkLogInitLevel("http_client", TO_FILE);
    MkLogChangeLevel(LOG_DEBUG);
    signal(SIGINT, SigHandle);// 设置退出信号
    CMkEventPool Pool;
    Pool.Start(10);
    CMkTimer Timer;
    Timer.StartTimerThread();
    MkMap<MkString, MkString> MapHeader;
    MapHeader["Authorization"] = "Basic YWRtaW46YWRtaW4=";
    CMkHttpHooker  *pClient = new  CMkHttpHooker(&Pool,&Timer);
    MkString strBody;
    MkString strJpg;
    char pbuf[LenHalfM] = { 0 };
    FILE *fp = fopen("C:/Workspace/media/11.jpg", "rb");
    if (nullptr != fp)
    {
        int nRet = fread(pbuf, 1, LenHalfM, fp);
        MkBase64Encode(MkString(pbuf, nRet), strJpg);
        fclose(fp);
    }
    Json::Value JsonData;
    JsonData["picData"] = strJpg;
    Json::Value Req;
    Req["action"] = "pictureSaved";
    Req["serverId"] = "111";
    Req["data"] = JsonData;
    strBody = Req.toStyledString();

    g_bRun = TRUE;
    while (g_bRun) {
        if (pClient) {
            pClient->SendRequest(MkHttpMethodPost, "http://127.0.0.1:8099/api/v1/cms-hook", MkMapString(), strBody, MapHeader, [pClient](const MkHttpStatusCode& StatusCode, const MkString& Res) {
                MkDebugLog("recv response code:%d  buffer:%s\n", StatusCode, Res.c_str());
            }, 20000);
        }
        CMkThread::ThreadSleep(100);
    }
    Timer.StopTimerThread();
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}

